<?php


namespace App\Filters;


use App\Models\Category;
use App\Models\User;
use Illuminate\Http\Request;

class QuestionFilter
{
    protected $request;
    protected $queryBuilder;
    protected $filters = ['category', 'user', 'popularity','unanswered'];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function apply($builder)
    {
        $this->queryBuilder = $builder;
        $filters = array_filter($this->request->only($this->filters));
        foreach ($filters as $filter => $value) {
            if (method_exists($this, $filter)) {
                $this->$filter($value, $this->queryBuilder);
            }
        }
        return $this->queryBuilder;
    }

    /**
     * @param $category_slug
     */
    private function category($category_slug)
    {
        $category = Category::query()->where('slug', '=', $category_slug)->first();
        $this->queryBuilder->where('category_id', $category->id);
    }

    /**
     * @param $username
     */
    private function user($username)
    {
        $user = User::query()->where('name', $username)->first();
        $this->queryBuilder->where('user_id', $user->id);
    }


    private function popularity()
    {
        $this->queryBuilder->orderByDesc('answers_count');
    }


    private function unanswered()
    {
        $this->queryBuilder->where('answers_count', 0);
    }
}
